﻿using System.Security.Cryptography;
using System.Text;
using System.Configuration;

namespace webapi.Helper
{
    public class HashHelper
    {
        private readonly byte[] _salt;

        public HashHelper()
        {
            String saltStr = "XINYONGCHENG";
            _salt = Encoding.UTF8.GetBytes(saltStr);
        }

        // 哈希密码并返回哈希值和盐  
        public string HashPassword(string password)
        {
            // 将密码转换为字节数组  
            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

            // 将盐和密码组合在一起  
            byte[] saltedPasswordBytes = new byte[_salt.Length + passwordBytes.Length];
            Buffer.BlockCopy(_salt, 0, saltedPasswordBytes, 0, _salt.Length);
            Buffer.BlockCopy(passwordBytes, 0, saltedPasswordBytes, _salt.Length, passwordBytes.Length);

            // 使用SHA-256对组合后的字节数组进行哈希处理  
            using (SHA256 sha256 = SHA256.Create())
            {
                byte[] hashBytes = sha256.ComputeHash(saltedPasswordBytes);
                string hashedPassword = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
                return hashedPassword;
            }
        }

        // 验证密码是否与存储的哈希匹配  
        public bool VerifyPassword(string password, string storedPwd)
        {
            // 将密码和盐组合在一起并计算哈希值  
            string testHash = HashPassword(password);

            // 比较哈希值是否相等  
            return testHash.SequenceEqual(storedPwd);
        }
    }
}
